<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>宝矿力水特能量补给大挑战</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #0a4a87; font-family: 'PingFang SC', sans-serif; }
        #gameContainer { position: relative; width: 100vw; height: 100vh; overflow: hidden; }
        #canvas { display: block; margin: 0 auto; }
        .ui-bar { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); color: white; z-index: 100; }
        .btn { position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%); padding: 10px 20px; background: #ff9800; color: white; border: none; border-radius: 25px; cursor: pointer; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.8); z-index: 200; }
        .modal-content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 20px; border-radius: 15px; text-align: center; }
    </style>
</head>
<body>
    <div id="gameContainer">
        <canvas id="canvas" width="375" height="667"></canvas>
        <div class="ui-bar">
            <div id="energyBar" style="width: 200px; height: 10px; background: #ffd700; border-radius: 5px;"></div>
        </div>
    </div>
    <button class="btn" id="restartBtn">重新挑战</button>
    <div class="modal" id="winModal">
        <div class="modal-content">
            <h2>关卡1通关！</h2>
            <p>收集进度：<span id="collectCount">0</span>/20</p>
            <button class="btn" onclick="goToNextLevel()">进入下一关</button>
        </div>
    </div>

    <script>
        // 全局变量
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');
        const screenWidth = window.innerWidth;
        const screenHeight = window.innerHeight;
        canvas.width = screenWidth;
        canvas.height = screenHeight;

        // 图片资源
        const images = {
            player: new Image(),
            item: new Image(),
            obstacle: new Image(),
            background: new Image()
        };
        
        // 设置图片路径（实际使用时需要替换为真实图片地址）
        // 设置图片路径（使用双反斜杠）
        images.player.src = 'https://gitee.com/helloworldljt/html5-enthusiast/raw/master/assets/player.png';
        images.item.src = 'https://gitee.com/helloworldljt/html5-enthusiast/raw/master/assets/item.png';
        images.obstacle.src = 'https://gitee.com/helloworldljt/html5-enthusiast/raw/master/assets/obstacle.png';
        images.background.src = 'https://gitee.com/helloworldljt/html5-enthusiast/raw/master/assets/1bffe5d4-efb2-4f42-b347-acf772c06796.jpg';
        // 玩家角色
        let player = {
            x: screenWidth/2,
            y: screenHeight-300,
            width: 200,
            height: 320,
            speed: 8,
            energy: 120 // 电解质能量值
        };

        // 道具（宝矿力电解质瓶）
        let items = [];
        let collectCount = 0;

        // 障碍物（水坑/光圈）
        let obstacles = [];

        // 游戏状态
        let gameRunning = false;
        let level = 1;
        let imagesLoaded = 0;
        const totalImages = Object.keys(images).length;

        // 初始化关卡1
        function initLevel1() {
            player.energy = 100;
            collectCount = 0;
            items = [];
            obstacles = [];
            spawnItems();
            spawnObstacles();
            updateEnergyBar();
        }

        // 生成道具
        function spawnItems() {
            for(let i=0; i<1; i++) {
                items.push({
                    x: Math.random()*screenWidth,
                    y: -100,
                    speed: 5 + Math.random()*1,
                    width: 120,
                    height: 180,
                    type: 'item' // 宝矿力瓶
                });
            }
        }

        // 生成障碍物
        function spawnObstacles() {
            obstacles.push({
                x: Math.random()*screenWidth,
                y: -100,
                speed: 4 + Math.random()*2,
                width: 200,
                height: 200,
                type: 'obstacle' // 水坑/光圈
            });
        }

        // 碰撞检测
        function checkCollision(a, b) {
            return !(a.x + a.width < b.x || 
                    a.x > b.x + b.width || 
                    a.y + a.height < b.y || 
                    a.y > b.y + b.height);
        }

        // 更新能量条
        function updateEnergyBar() {
            document.getElementById('energyBar').style.width = `${player.energy}px`;
            if(player.energy <= 0) gameOver();
        }

        // 游戏主循环
        function gameLoop() {
            if(!gameRunning) return;
            
            // 清空画布
            if(images.background.complete) {
                // 使用背景图
                ctx.drawImage(images.background, 0, 0, screenWidth, screenHeight);
            } else {
                // 备用纯色背景
                ctx.fillStyle = '#0a4a87';
                ctx.fillRect(0, 0, screenWidth, screenHeight);
            }
            
            // 绘制玩家
            if(images.player.complete) {
                ctx.drawImage(images.player, player.x, player.y, player.width, player.height);
            } else {
                ctx.fillStyle = '#ffffff';
                ctx.fillRect(player.x, player.y, player.width, player.height);
            }
            
            // 处理道具下落
            items.forEach((item, index) => {
                item.y += item.speed;
                if(item.y > screenHeight) items.splice(index, 1);
                
                // 绘制道具
                if(images.item.complete) {
                    ctx.drawImage(images.item, item.x, item.y, item.width, item.height);
                } else {
                    ctx.fillStyle = '#00bcd4';
                    ctx.fillRect(item.x, item.y, item.width, item.height);
                }
                
                // 收集检测
                if(checkCollision(player, item)) {
                    collectCount++;
                    items.splice(index, 1);
                    spawnItems(); // 补充新道具
                    player.energy = Math.min(player.energy + 20, 100); // 补充能量
                    if(collectCount >= 60) levelWin(); // 通关条件
                }
            });

            // 处理障碍物下落
            obstacles.forEach((obs, index) => {
                obs.y += obs.speed;
                if(obs.y > screenHeight) obstacles.splice(index, 1);
                
                // 绘制障碍物
                if(images.obstacle.complete) {
                    ctx.drawImage(images.obstacle, obs.x, obs.y, obs.width, obs.height);
                } else {
                    ctx.fillStyle = '#ff5722';
                    ctx.fillRect(obs.x, obs.y, obs.width, obs.height);
                }
                
                // 碰撞消耗能量
                if(checkCollision(player, obs)) {
                    player.energy -= 3;
                    obstacles.splice(index, 1);
                }
            });

            // 持续消耗能量（模拟脱水）
            player.energy = Math.max(player.energy - 0.2, 0);
            updateEnergyBar();

            requestAnimationFrame(gameLoop);
        }

        // 关卡胜利
        function levelWin() {
            gameRunning = false;
            document.getElementById('collectCount').textContent = collectCount;
            document.getElementById('winModal').style.display = 'block';
        }

        // 游戏失败
        function gameOver() {
            gameRunning = false;
            alert('能量耗尽！点击重试补充电解质吧～');
        }

        // 控制移动（触屏+键盘）
        function handleInput(e) {
            if(!gameRunning) return;
            let x = e.type.startsWith('touch') ? e.touches[0].clientX : e.clientX;
            player.x = Math.max(player.width/2, Math.min(screenWidth - player.width/2, x));
        }

        // 初始化游戏
        function startGame() {
            // 检查所有图片是否加载完成
            if(imagesLoaded < totalImages) {
                setTimeout(startGame, 100);
                return;
            }
            
            gameRunning = true;
            initLevel1();
            gameLoop();
            // 绑定输入事件
            canvas.addEventListener('touchmove', handleInput);
            window.addEventListener('mousemove', handleInput);
        }

        // 图片加载监听
        for(let key in images) {
            images[key].onload = function() {
                imagesLoaded++;
                console.log(`${key} 图片加载完成`);
            };
            images[key].onerror = function() {
                imagesLoaded++;
                console.error(`${key} 图片加载失败`);
            };
        }

        // 页面加载时启动第一关
        document.addEventListener('DOMContentLoaded', function() {
            // 等待图片加载完成后再启动游戏
            if(imagesLoaded < totalImages) {
                setTimeout(startGame, 100);
            } else {
                startGame();
            }
        });

        // 重启按钮
        document.getElementById('restartBtn').addEventListener('click', () => {
            startGame();
            document.getElementById('winModal').style.display = 'none';
        });

        // 适配屏幕旋转（简化版）
        window.addEventListener('orientationchange', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
        });
    </script>
</body>
</html>